import { app, shell, BrowserWindow, ipcMain } from 'electron'
import log from 'electron-log'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
//import { SerialPort } from 'serialport'
import {autoUpdater} from 'electron-updater'

log.transports.file.level = 'info'

// 设置自动更新
autoUpdater.autoDownload = false // 不自动下载，让用户选择
autoUpdater.autoInstallOnAppQuit = false // 退出时自动安装
autoUpdater.logger = log

let mainWindow

// 确保应用是单实例的
const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  // 如果已经有一个实例在运行，就退出当前实例
  app.quit()
} else {
  app.on('second-instance', () => {
    // 当运行第二个实例时，将会聚焦到 mainWindow 窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
    }
  })
}

function createWindow(): void {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1280,
    height: 1024,
    show: false,
	  frame: false, // 无边框窗口
    autoHideMenuBar: true,
    icon,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  // 处理窗口操作
  ipcMain.handle('window-minimize', () => {
    mainWindow.minimize();
  })

  ipcMain.handle('window-maximize', () => {
    if (mainWindow.isMaximized()) {
      mainWindow.unmaximize();
    } else {
      mainWindow.maximize();
    }
  });

  ipcMain.handle('window-close', () => {
    mainWindow.close();
  });

  ipcMain.handle('check-for-updates', async () => {
    return await autoUpdater.checkForUpdates()
  });

  ipcMain.handle('download-update', async () => {

    return await autoUpdater.downloadUpdate()
  })

  ipcMain.handle('quit-and-install', () => {
    autoUpdater.quitAndInstall()
  })

  // 可选：在关闭前确认
  //mainWindow.on('close', (event) => {
    // 如果需要确认关闭，可以在这里处理
    // event.preventDefault();
    // 显示确认对话框
  //});



  mainWindow.on('ready-to-show', () => {
    mainWindow.show()

/**
    new SerialPort({
        path: 'COM1', // 串口号
        baudRate: 56000, // 波特率
        autoOpen: true // 是否自动打开端口
      },
      function (err) {
        if (err) {
          return console.log('打开失败: ', err.message)
        }
        console.log('打开成功')
      })
	  **/


  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
    mainWindow.webContents.openDevTools()
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}


// 更新事件处理
autoUpdater.on('checking-for-update', () => {
  console.log('检查更新中...')
  mainWindow.webContents.send('update-status', '检查更新中...');
});


autoUpdater.on('update-available', (info) => {
  console.log('发现新版本:', info);
  mainWindow.webContents.send('update-available', info);

  // 询问用户是否下载更新

  /*
  dialog.showMessageBox(mainWindow, {
    type: 'info',
    title: '发现新版本',
    message: `发现新版本 ${info.version}，是否立即下载？`,
    buttons: ['下载', '取消']
  }).then(result => {
    if (result.response === 0) {
      autoUpdater.downloadUpdate();
    }
  });
  */
});

autoUpdater.on('update-not-available', () => {
  mainWindow.webContents.send('update-status', '已是最新版本');
});

autoUpdater.on('download-progress', (progressObj) => {
  console.log('下载进度:', progressObj)
  mainWindow.webContents.send('download-progress', progressObj)
})

autoUpdater.on('update-downloaded', (info) => {
  mainWindow.webContents.send('update-downloaded', info);

  // 询问用户是否立即安装
  /**
  dialog.showMessageBox(mainWindow, {
    type: 'info',
    title: '更新下载完成',
    message: '新版本已下载完成，是否立即重启应用安装更新？',
    buttons: ['立即重启', '稍后']
  }).then(result => {
    if (result.response === 0) {
      autoUpdater.quitAndInstall();
    }
  });
  */
});

autoUpdater.on('error', (err) => {
  mainWindow.webContents.send('update-error', err.message);
});


// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.xmappservice.scanner')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  setTimeout(() => {
    autoUpdater.checkForUpdates();
  }, 5000);
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
